package lambdasinaction.chap3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by ThinkPad on 2017/8/16.
 */
public class ExecuteAround {

    public static void main(String... args) throws IOException {
        System.out.println("classpath路径:" + ExecuteAround.class.getClassLoader().getResource("").getPath());
        System.out.println("当前类加载路径:" + ExecuteAround.class.getResource("").getPath());
        System.out.println("data.txt路径:" + ExecuteAround.class.getResource("data.txt").getPath());
        System.out.println("data.txt路径2:" + ExecuteAround.class.getClassLoader().getResource("lambdasinaction/chap3/data.txt")
                .getPath());
        String result = processFileLimited();
        System.out.println(result);
        System.out.println("----");
        String oneLine = processFile((BufferedReader br) -> br.readLine());
        System.out.println(oneLine);
        String twoLine = processFile((BufferedReader br) -> br.readLine() + br.readLine());
        System.out.println(twoLine);
    }

    @FunctionalInterface
    public interface BufferedReaderProcessor {
        String process(BufferedReader b) throws IOException;
    }

    public static String processFileLimited() throws IOException {
        try (BufferedReader br =
                     new BufferedReader(new FileReader(
                             ExecuteAround.class.getResource("data.txt")
                             .getPath()
                     ))) {
            return br.readLine();
        }
    }

    public static String processFile(BufferedReaderProcessor p) throws  IOException {
        try (BufferedReader br =
                     new BufferedReader(new FileReader(
                             ExecuteAround.class.getClassLoader().getResource("lambdasinaction/chap3/data.txt")
                             .getPath()
                     ))) {
            return p.process(br);
        }
    }
}